package repository

import (
	"github.com/google/uuid"
	"gorm.io/gorm"

	"forum/pkg/domain"
)

type postRepository struct {
	DB *gorm.DB
}

func NewPostRepository(db *gorm.DB, thread domain.Thread) domain.PostRepository {
	return &postRepository{
		DB: db,
	}
}

func (rep *postRepository) CreatePost(post *domain.Post) error {
	// create uuid for User
	post.UUID = uuid.New().String()

	return rep.DB.Create(post).Error
}

func (rep *postRepository) DeletePost(postID string) error {
	return rep.DB.Delete(&domain.Post{}, postID).Error
}

func (rep *postRepository) UpdatePost(post *domain.Post) error {
	return rep.DB.Save(post).Error
}

func (rep *postRepository) GetPosts() ([]domain.Post, error) {
	posts := make([]domain.Post, 0)
	err := rep.DB.Find(&posts).Error
	return posts, err
}

func (rep *postRepository) GetPost(postID string) (domain.Post, error) {
	p := domain.Post{}
	err := rep.DB.First(&p, "uuid = ?", postID).Error
	return p, err
}
